package a66weding.com.jiehuntong.activity.me;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.ProvinceCitySelectBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.CacheUtils;
import a66weding.com.jiehuntong.dao.db.address.AddressDao;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;

/**
 * 这是我的-个人信息-收货地址-添加收货地址界面
 */
public class MeUserAddaddressActivity extends MeBaseActivity implements View.OnClickListener, OnNetResultListener {
    private LinearLayout mBackLay;
    private TextView mBackContentTv;
    private TextView mHeaderTitleTv;
    private RelativeLayout mHeaderRightRlay;
    private EditText mNameEt;
    private EditText mPhoneEt;
    private TextView mCityTv;
    private EditText mAddressEt;
    private Button mCommitBt;
    private String name;
    private String phone;
    private String city;
    private String address;
    private RelativeLayout mCityRl;
    private CheckBox checkBox;
    private String pName;
    private String cName;
    private String aName;
    private boolean islogin;
    private int memberId;
    private boolean isCanClick=true;
    private boolean isCanCommit=true;

    private static final int CLICKABLE=1;
    private static final int COMMITABLE=2;
    private static final int DBADDRESS=7;

    private AddressDao addressDao;
    private List<ProvinceCitySelectBean.ResultBean> result;

    private Handler mHandler=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                    case CLICKABLE:
                        isCanClick=true;
                    break;
                    case COMMITABLE:
                        isCanCommit=true;
                    break;
                case DBADDRESS:
                    initDataBase();
                    break;

            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_user_addaddress);
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("MeUserAddaddressActivity", this);

        initview();

        initdata();
    }

    private void initdata() {
        boolean isAddressDbCreate = CacheUtils.getBooleanFromCache(this, "isAddressDbCreate");
        if(isAddressDbCreate) {

        }else{
            addressDao = new AddressDao(this);
            String url=RequestCode.get_PCAList;
            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url, this, ProvinceCitySelectBean.class, RequestCode.get_PCAList);
            HttpHandleUtil.executeCommonGet(this,httpRequestBean);

        }
    }


    private void initview() {
        mBackLay = (LinearLayout) findViewById(R.id.llay_header_back);
        mBackContentTv = (TextView) findViewById(R.id.tv_header_backcontent);
        mHeaderTitleTv = (TextView) findViewById(R.id.tv_header_title);
        mHeaderRightRlay = (RelativeLayout) findViewById(R.id.rlay_header_rightfunc);
        mNameEt = (EditText) findViewById(R.id.et_add_name);
        mPhoneEt = (EditText) findViewById(R.id.et_add_phone);
        mCityTv = (TextView) findViewById(R.id.et_add_city);
        mAddressEt = (EditText) findViewById(R.id.et_add_address);
        mCommitBt = (Button) findViewById(R.id.btn_commit);
        mCityRl = (RelativeLayout) findViewById(R.id.rl_city);
        checkBox = (CheckBox) findViewById(R.id.checkBox);

        mBackContentTv.setText("返回");
        mHeaderTitleTv.setText("添加收获地址");
        mHeaderRightRlay.setVisibility(View.GONE);

        mBackLay.setOnClickListener(this);
        mCommitBt.setOnClickListener(this);
        mCityRl.setOnClickListener(this);


    }

    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences sp = getSharedPreferences("city",Activity.MODE_PRIVATE);
        String city = sp.getString("city","");
        pName = sp.getString("pName","");
        cName = sp.getString("cName","");
        aName = sp.getString("aName","");
            mCityTv.setText(city);


    }

    @Override
    protected void onPause() {
        super.onPause();
        SharedPreferences sp = getSharedPreferences("city", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("city","请设置您的收货地址");
        editor.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llay_header_back: //点击返回,关闭界面
                finish();
                break;
            case R.id.rl_city: //设置您的收货地址,则添加收货地址
                if(isCanClick) {

                    boolean isAddressDbCreate = CacheUtils.getBooleanFromCache(this, "isAddressDbCreate");
                    if(isAddressDbCreate) {
                        Intent intent = new Intent(this,MeSelectCityActivity.class);
                        startActivity(intent);
                        mHandler.sendEmptyMessageDelayed(CLICKABLE,3000);
                        isCanClick=false;
                    }else{
                        CUtils.showToast("抱歉，数据获取错误，请重新登陆后重试");
                    }
                }
                break;
            case R.id.btn_commit: //点击提交按钮,添加地址

                if(isCanCommit) {

                    mHandler.sendEmptyMessageDelayed(COMMITABLE,3000);
                    isCanCommit=false;
                name = mNameEt.getText().toString().trim();
                phone = mPhoneEt.getText().toString().trim();
                address = mAddressEt.getText().toString().trim();
                if(TextUtils.isEmpty(name)) {
                    CUtils.showToast("收货人的姓名不能为空");
                    return;
                } else if(TextUtils.isEmpty(phone)) {
                    CUtils.showToast("收货人的电话不能为空");
                    return;
                }
                else if(mCityTv.getText().equals("请设置您的收货地址")) {
                    CUtils.showToast("收货地址不能为空");
                    return;
                }
                else if(TextUtils.isEmpty(address)) {
                    CUtils.showToast("详细地址不能为空");
                    return;
                }
                // 使用正则匹配手机号是否合格
                Pattern p = Pattern.compile("[1][34578]\\d{9}");
                Matcher m = p.matcher(phone);
                boolean rs = m.matches();
                if(!rs ) {
                    CUtils.showToast("您输入的手机号码格式有误,请重新输入");
                    return;
                }
                // 获取到id
                islogin = ((GlobalApplication) getApplication()).isLogin();
                if(islogin) {
                    memberId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
                }

                // 获取到是否为默认收货地址
                int checked = 0;
                if(checkBox.isChecked()) {
                    checked = 1;
                } else {
                    checked = 0;
                }
                //发起网络请求,向服务器添加地址
                String url= UrlDealUtil.getRealUrlNoId(RequestCode.ADD_RECEIPTADDRESS);
                HashMap requestParams=new HashMap();

                requestParams.put("nvc_Consignee",""+name);
                requestParams.put("nvc_MobilePhone",""+phone);
                requestParams.put("nvc_StreetAddress",""+address);
                requestParams.put("pName",""+pName);
                requestParams.put("cName",""+cName);
                requestParams.put("aName",""+aName);
                requestParams.put("i_MemberId",""+ memberId);
                requestParams.put("IsDefault",""+checked);

                HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                        this, CommonResultBean.class, RequestCode.ADD_RECEIPTADDRESS, requestParams);
                HttpHandleUtil.executeCommonPost(this,httpRequestBean);
                }

                break;
        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if(data instanceof CommonResultBean) {
            Toast.makeText(this,"地址添加成功",Toast.LENGTH_SHORT).show();

        }else if(data instanceof ProvinceCitySelectBean){

            ProvinceCitySelectBean selectData= (ProvinceCitySelectBean) data;

            switch (selectData.getResCode()) {
                case "0000":
                    result = selectData.getResult();
                    mHandler.sendEmptyMessage(DBADDRESS);

                    break;
                case "0003":

                    break;
            }

        }


        finish();
    }

    @Override
    public void onError(ErrorBean errorBean) {
        Toast.makeText(this,"地址添加失败",Toast.LENGTH_SHORT).show();
    }


    private void initDataBase() {
        if(result!=null) {

            boolean isAdd = addressDao.addAllAddress(result);
            if(isAdd) {
                CacheUtils.setBooleanToCache(this,"isAddressDbCreate",true);
            }else{
                CacheUtils.setBooleanToCache(this,"isAddressDbCreate",false);

            }
        }

    }
}
